Yes. The idea of encapsulation is to hide the details of an object from other sections of the software. Some of the details might be methods.
A private method can be used only by the other methods of the object. Outside of the object a private method is not visible.
Say that the bank wants to keep track of how many
times each the balance of checking account has been altered.
(This might be done as a security measure.)
To do this, a use count is added to the data of the
CheckingAccount
class.
The processDeposit()
and processCheck()
methods
call incrementUse()
to increment the use count each time they are used.
We want the use count to change for these two reasons only,
so the incrementUse()
method
and the variable useCount
are made
private
.
class CheckingAccount { // data-declarations private String accountNumber; private String accountHolder; private int balance; private int useCount = 0; private void incrementUse() { } void processDeposit( int amount ) { incrementUse(); balance = balance + amount ; } void processCheck( int amount ) { int charge; incrementUse(); if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; } // other methods . . . }
Fill in the blank so that the new private method increments the use count.